#include "mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QApplication>
#include <QStatusBar>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_stackedWidget(nullptr)
    , m_homeWidget(nullptr)
    , m_backButton(nullptr)
    , m_statusLabel(nullptr)
    , m_systemTimer(nullptr)
    , m_serialWidget(nullptr)
    , m_networkWidget(nullptr)
    , m_mqttWidget(nullptr)
    , m_videoWidget(nullptr)
    , m_musicWidget(nullptr)
    , m_weatherWidget(nullptr)
    , m_cameraWidget(nullptr)
    , m_galleryWidget(nullptr)
    , m_opencvWidget(nullptr)
    , m_paintWidget(nullptr)
    , m_settingsWidget(nullptr)
    , m_currentTheme(0)
    , m_lastTotalTime(0)
    , m_lastIdleTime(0)
{
    setupUI();
    
    // 加载默认主题
    loadStyleSheet(m_currentTheme);
    
    // 启动系统信息更新定时器
    m_systemTimer = new QTimer(this);
    connect(m_systemTimer, &QTimer::timeout, this, &MainWindow::onUpdateSystemInfo);
    m_systemTimer->start(1000); // 每秒更新一次
    
    // 立即更新一次系统信息
    updateSystemInfo();
}

MainWindow::~MainWindow()
{
}

void MainWindow::setupUI()
{
    // 设置窗口标题和尺寸
    setWindowTitle("IMX6ULL 桌面应用");
    setFixedSize(1024, 600);
    
    // 创建中心容器
    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    
    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);
    
    // 创建堆栈窗口
    m_stackedWidget = new QStackedWidget(centralWidget);
    mainLayout->addWidget(m_stackedWidget);
    
    // 创建返回按钮（初始隐藏）- 必须在stackedWidget之后创建，确保在最上层
    m_backButton = new QPushButton("返回", centralWidget);
    m_backButton->setFixedSize(100, 40);
    m_backButton->setObjectName("backButton");
    m_backButton->hide();
    connect(m_backButton, &QPushButton::clicked, this, &MainWindow::onBackToHome);
    
    // 将返回按钮设置为悬浮在左上角，并提升到最上层
    m_backButton->move(10, 10);
    m_backButton->raise();
    
    // 创建主页图标网格
    createIconGrid();
    m_stackedWidget->addWidget(m_homeWidget); // 索引0
    
    // 创建串口助手Widget
    m_serialWidget = new SerialWidget();
    m_stackedWidget->addWidget(m_serialWidget); // 索引1
    
    // 创建网络助手Widget（待实现）
    m_networkWidget = new QWidget();
    QLabel *networkLabel = new QLabel("网络助手界面\n（待实现）", m_networkWidget);
    networkLabel->setAlignment(Qt::AlignCenter);
    networkLabel->setStyleSheet("font-size: 24px;");
    QVBoxLayout *networkLayout = new QVBoxLayout(m_networkWidget);
    networkLayout->addWidget(networkLabel);
    m_stackedWidget->addWidget(m_networkWidget); // 索引2
    
    // 创建MQTT测试Widget
    m_mqttWidget = new MqttWidget();
    m_stackedWidget->addWidget(m_mqttWidget); // 索引3
    
    // 创建视频播放Widget
    m_videoWidget = new VideoPlayerWidget();
    m_stackedWidget->addWidget(m_videoWidget); // 索引4
    
    m_musicWidget = new QWidget();
    QLabel *musicLabel = new QLabel("音乐播放界面\n（待实现）", m_musicWidget);
    musicLabel->setAlignment(Qt::AlignCenter);
    musicLabel->setStyleSheet("font-size: 24px;");
    QVBoxLayout *musicLayout = new QVBoxLayout(m_musicWidget);
    musicLayout->addWidget(musicLabel);
    m_stackedWidget->addWidget(m_musicWidget); // 索引5
    
    m_weatherWidget = new QWidget();
    QLabel *weatherLabel = new QLabel("天气预报界面\n（待实现）", m_weatherWidget);
    weatherLabel->setAlignment(Qt::AlignCenter);
    weatherLabel->setStyleSheet("font-size: 24px;");
    QVBoxLayout *weatherLayout = new QVBoxLayout(m_weatherWidget);
    weatherLayout->addWidget(weatherLabel);
    m_stackedWidget->addWidget(m_weatherWidget); // 索引6
    
    m_cameraWidget = new QWidget();
    QLabel *cameraLabel = new QLabel("照相机界面\n（待实现）", m_cameraWidget);
    cameraLabel->setAlignment(Qt::AlignCenter);
    cameraLabel->setStyleSheet("font-size: 24px;");
    QVBoxLayout *cameraLayout = new QVBoxLayout(m_cameraWidget);
    cameraLayout->addWidget(cameraLabel);
    m_stackedWidget->addWidget(m_cameraWidget); // 索引7
    
    m_galleryWidget = new QWidget();
    QLabel *galleryLabel = new QLabel("相册界面\n（待实现）", m_galleryWidget);
    galleryLabel->setAlignment(Qt::AlignCenter);
    galleryLabel->setStyleSheet("font-size: 24px;");
    QVBoxLayout *galleryLayout = new QVBoxLayout(m_galleryWidget);
    galleryLayout->addWidget(galleryLabel);
    m_stackedWidget->addWidget(m_galleryWidget); // 索引8
    
    m_opencvWidget = new QWidget();
    QLabel *opencvLabel = new QLabel("OpenCV检测界面\n（待实现）", m_opencvWidget);
    opencvLabel->setAlignment(Qt::AlignCenter);
    opencvLabel->setStyleSheet("font-size: 24px;");
    QVBoxLayout *opencvLayout = new QVBoxLayout(m_opencvWidget);
    opencvLayout->addWidget(opencvLabel);
    m_stackedWidget->addWidget(m_opencvWidget); // 索引9
    
    m_paintWidget = new QWidget();
    QLabel *paintLabel = new QLabel("画图工具界面\n（待实现）", m_paintWidget);
    paintLabel->setAlignment(Qt::AlignCenter);
    paintLabel->setStyleSheet("font-size: 24px;");
    QVBoxLayout *paintLayout = new QVBoxLayout(m_paintWidget);
    paintLayout->addWidget(paintLabel);
    m_stackedWidget->addWidget(m_paintWidget); // 索引10
    
    m_settingsWidget = new QWidget();
    QLabel *settingsLabel = new QLabel("设置界面\n（待实现）", m_settingsWidget);
    settingsLabel->setAlignment(Qt::AlignCenter);
    settingsLabel->setStyleSheet("font-size: 24px;");
    QVBoxLayout *settingsLayout = new QVBoxLayout(m_settingsWidget);
    settingsLayout->addWidget(settingsLabel);
    m_stackedWidget->addWidget(m_settingsWidget); // 索引11
    
    // 创建状态栏
    createStatusBar();
    
    // 默认显示主页
    m_stackedWidget->setCurrentIndex(0);
}

// 创建图标网格
void MainWindow::createIconGrid()
{
    m_homeWidget = new QWidget();
    QVBoxLayout *homeLayout = new QVBoxLayout(m_homeWidget);
    homeLayout->setContentsMargins(20, 60, 20, 10); // 顶部留出空间给返回按钮
    homeLayout->setSpacing(10);
    
    // 标题标签
    QLabel *titleLabel = new QLabel("IMX6ULL 桌面应用", m_homeWidget);
    titleLabel->setObjectName("titleLabel");
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setFixedHeight(50);
    homeLayout->addWidget(titleLabel);
    
    // 图标网格布局
    QGridLayout *gridLayout = new QGridLayout();
    gridLayout->setSpacing(20);
    gridLayout->setContentsMargins(40, 20, 40, 20);
    
    // 创建12个功能图标按钮
    QPushButton *serialBtn = createIconButton(":/icons/serial.png", "串口助手");
    QPushButton *networkBtn = createIconButton(":/icons/network.png", "网络助手");
    QPushButton *mqttBtn = createIconButton(":/icons/mqtt.png", "MQTT测试");
    QPushButton *videoBtn = createIconButton(":/icons/video.png", "视频播放");
    QPushButton *musicBtn = createIconButton(":/icons/music.png", "音乐播放");
    QPushButton *weatherBtn = createIconButton(":/icons/weather.png", "天气预报");
    QPushButton *cameraBtn = createIconButton(":/icons/camera.png", "照相机");
    QPushButton *galleryBtn = createIconButton(":/icons/gallery.png", "相册");
    QPushButton *opencvBtn = createIconButton(":/icons/opencv.png", "OpenCV检测");
    QPushButton *paintBtn = createIconButton(":/icons/paint.png", "画图工具");
    QPushButton *wallpaperBtn = createIconButton(":/icons/wallpaper.png", "壁纸切换");
    QPushButton *settingsBtn = createIconButton(":/icons/settings.png", "设置");
    
    // 连接信号槽
    connect(serialBtn, &QPushButton::clicked, this, &MainWindow::onSerialClicked);
    connect(networkBtn, &QPushButton::clicked, this, &MainWindow::onNetworkClicked);
    connect(mqttBtn, &QPushButton::clicked, this, &MainWindow::onMqttClicked);
    connect(videoBtn, &QPushButton::clicked, this, &MainWindow::onVideoClicked);
    connect(musicBtn, &QPushButton::clicked, this, &MainWindow::onMusicClicked);
    connect(weatherBtn, &QPushButton::clicked, this, &MainWindow::onWeatherClicked);
    connect(cameraBtn, &QPushButton::clicked, this, &MainWindow::onCameraClicked);
    connect(galleryBtn, &QPushButton::clicked, this, &MainWindow::onGalleryClicked);
    connect(opencvBtn, &QPushButton::clicked, this, &MainWindow::onOpenCVClicked);
    connect(paintBtn, &QPushButton::clicked, this, &MainWindow::onPaintClicked);
    connect(wallpaperBtn, &QPushButton::clicked, this, &MainWindow::onWallpaperClicked);
    connect(settingsBtn, &QPushButton::clicked, this, &MainWindow::onSettingsClicked);
    
    // 添加到网格布局（3行4列）
    gridLayout->addWidget(serialBtn, 0, 0);
    gridLayout->addWidget(networkBtn, 0, 1);
    gridLayout->addWidget(mqttBtn, 0, 2);
    gridLayout->addWidget(videoBtn, 0, 3);
    
    gridLayout->addWidget(musicBtn, 1, 0);
    gridLayout->addWidget(weatherBtn, 1, 1);
    gridLayout->addWidget(cameraBtn, 1, 2);
    gridLayout->addWidget(galleryBtn, 1, 3);
    
    gridLayout->addWidget(opencvBtn, 2, 0);
    gridLayout->addWidget(paintBtn, 2, 1);
    gridLayout->addWidget(wallpaperBtn, 2, 2);
    gridLayout->addWidget(settingsBtn, 2, 3);
    
    homeLayout->addLayout(gridLayout);
    homeLayout->addStretch();
}

// 创建状态栏
void MainWindow::createStatusBar()
{
    // 创建状态栏标签
    m_statusLabel = new QLabel(this);
    m_statusLabel->setObjectName("statusLabel");
    m_statusLabel->setAlignment(Qt::AlignCenter);
    m_statusLabel->setFixedHeight(30);
    
    // 添加到主窗口状态栏
    statusBar()->addWidget(m_statusLabel, 1);
    statusBar()->setStyleSheet("QStatusBar { background-color: #2c3e50; }");
}

// 创建图标按钮
QPushButton* MainWindow::createIconButton(const QString &iconPath, const QString &text)
{
    QPushButton *button = new QPushButton(m_homeWidget);
    button->setText(text);
    button->setObjectName("iconButton");
    button->setFixedSize(200, 120);
    
    // 设置图标（如果存在）
    QIcon icon(iconPath);
    if (!icon.isNull()) {
        button->setIcon(icon);
        button->setIconSize(QSize(60, 60));
    }
    
    return button;
}

// 加载样式表
void MainWindow::loadStyleSheet(int themeIndex)
{
    QString qssFile = QString(":/styles/style%1.qss").arg(themeIndex + 1);
    QFile file(qssFile);
    
    if (file.open(QFile::ReadOnly | QFile::Text)) {
        QTextStream stream(&file);
        QString styleSheet = stream.readAll();
        qApp->setStyleSheet(styleSheet);
        file.close();
        qDebug() << "加载主题:" << qssFile;
    } else {
        qDebug() << "无法加载主题文件:" << qssFile;
        // 使用默认样式
        applyDefaultStyle();
    }
}

// 应用默认样式
void MainWindow::applyDefaultStyle()
{
    // 默认样式（内嵌）
    QString defaultStyle = R"(
        QMainWindow {
            background-color: #ecf0f1;
        }
        
        #titleLabel {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        #iconButton {
            background-color: #ffffff;
            border: 2px solid #bdc3c7;
            border-radius: 10px;
            font-size: 14px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        #iconButton:hover {
            background-color: #ecf0f1;
            border-color: #3498db;
        }
        
        #iconButton:pressed {
            background-color: #bdc3c7;
        }
        
        #backButton {
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 14px;
            font-weight: bold;
        }
        
        #backButton:hover {
            background-color: #2980b9;
        }
        
        #backButton:pressed {
            background-color: #21618c;
        }
        
        #statusLabel {
            color: white;
            font-size: 12px;
            background-color: #2c3e50;
        }
    )";
    
    qApp->setStyleSheet(defaultStyle);
}

// 更新系统信息
void MainWindow::updateSystemInfo()
{
    float cpuUsage = getCpuUsage();
    int totalMB, usedMB;
    getMemoryInfo(totalMB, usedMB);
    QString currentTime = QTime::currentTime().toString("hh:mm:ss");
    
    QString statusText = QString("CPU: %1% | 内存: %2MB/%3MB | 时间: %4")
                            .arg(cpuUsage, 0, 'f', 1)
                            .arg(usedMB)
                            .arg(totalMB)
                            .arg(currentTime);
    
    m_statusLabel->setText(statusText);
}

// 获取CPU使用率
float MainWindow::getCpuUsage()
{
    QFile file("/proc/stat");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return 0.0f;
    }
    
    QTextStream in(&file);
    QString line = in.readLine(); // 读取第一行 "cpu ..."
    file.close();
    
    QStringList parts = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);
    if (parts.size() < 5) {
        return 0.0f;
    }
    
    // 解析CPU时间（至少需要前8个字段）
    // cpu字段: user nice system idle iowait irq softirq steal guest guest_nice
    unsigned long long user = parts[1].toULongLong();
    unsigned long long nice = parts[2].toULongLong();
    unsigned long long system = parts[3].toULongLong();
    unsigned long long idle = parts[4].toULongLong();
    unsigned long long iowait = parts.size() > 5 ? parts[5].toULongLong() : 0;
    unsigned long long irq = parts.size() > 6 ? parts[6].toULongLong() : 0;
    unsigned long long softirq = parts.size() > 7 ? parts[7].toULongLong() : 0;
    unsigned long long steal = parts.size() > 8 ? parts[8].toULongLong() : 0;
    
    // 计算总时间（包含所有CPU时间）
    unsigned long long totalTime = user + nice + system + idle + iowait + irq + softirq + steal;
    // idle时间包括idle和iowait
    unsigned long long idleTime = idle + iowait;
    
    // 计算差值
    if (m_lastTotalTime == 0) {
        // 第一次采样
        m_lastTotalTime = totalTime;
        m_lastIdleTime = idleTime;
        return 0.0f;
    }
    
    unsigned long long totalDelta = totalTime - m_lastTotalTime;
    unsigned long long idleDelta = idleTime - m_lastIdleTime;
    
    m_lastTotalTime = totalTime;
    m_lastIdleTime = idleTime;
    
    if (totalDelta == 0) {
        return 0.0f;
    }
    
    float usage = 100.0f * (1.0f - (float)idleDelta / (float)totalDelta);
    return usage;
}

// 获取内存信息
void MainWindow::getMemoryInfo(int &totalMB, int &usedMB)
{
    totalMB = 0;
    usedMB = 0;
    
    QFile file("/proc/meminfo");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开 /proc/meminfo:" << file.errorString();
        return;
    }
    
    // 读取全部内容
    QByteArray data = file.readAll();
    file.close();
    
    if (data.isEmpty()) {
        return;
    }
    
    // 转换为字符串并按行分割
    QString content = QString::fromUtf8(data);
    QStringList lines = content.split('\n', QString::SkipEmptyParts);
    
    int memTotal = 0;
    int memFree = 0;
    int memAvailable = 0;
    int buffers = 0;
    int cached = 0;
    
    // 解析前10行（足够获取所需信息）
    for (int i = 0; i < lines.size() && i < 10; i++) {
        QString line = lines[i];
        
        // 使用冒号分割键值对
        int colonPos = line.indexOf(':');
        if (colonPos < 0) {
            continue;
        }
        
        QString key = line.left(colonPos).trimmed();
        QString value = line.mid(colonPos + 1).trimmed();
        
        // 移除单位 "kB"
        value = value.remove("kB").trimmed();
        
        // 解析各个字段
        if (key == "MemTotal") {
            memTotal = value.toInt();
        } else if (key == "MemAvailable") {
            memAvailable = value.toInt();
        } else if (key == "MemFree") {
            memFree = value.toInt();
        } else if (key == "Buffers") {
            buffers = value.toInt();
        } else if (key == "Cached") {
            cached = value.toInt();
        }
        
        // 提前退出优化：获取到所需信息后立即退出
        if (memTotal > 0 && (memAvailable > 0 || (memFree > 0 && buffers > 0 && cached > 0))) {
            break;
        }
    }
    
    // 转换为MB
    totalMB = memTotal / 1024;
    
    // 优先使用 MemAvailable（Linux 3.14+），如果不存在则用传统计算方式
    if (memAvailable > 0) {
        usedMB = (memTotal - memAvailable) / 1024;
    } else {
        // 传统计算方式：Used = Total - Free - Buffers - Cached
        usedMB = (memTotal - memFree - buffers - cached) / 1024;
    }
}

// 串口助手
void MainWindow::onSerialClicked()
{
    m_stackedWidget->setCurrentIndex(1);
    m_backButton->show();
}

// 网络助手
void MainWindow::onNetworkClicked()
{
    m_stackedWidget->setCurrentIndex(2);
    m_backButton->show();
}

// MQTT测试
void MainWindow::onMqttClicked()
{
    m_stackedWidget->setCurrentIndex(3);
    m_backButton->show();
}

// 视频播放
void MainWindow::onVideoClicked()
{
    m_stackedWidget->setCurrentIndex(4);
    m_backButton->show();
}

// 音乐播放
void MainWindow::onMusicClicked()
{
    m_stackedWidget->setCurrentIndex(5);
    m_backButton->show();
}

// 天气预报
void MainWindow::onWeatherClicked()
{
    m_stackedWidget->setCurrentIndex(6);
    m_backButton->show();
}

// 照相机
void MainWindow::onCameraClicked()
{
    m_stackedWidget->setCurrentIndex(7);
    m_backButton->show();
}

// 相册
void MainWindow::onGalleryClicked()
{
    m_stackedWidget->setCurrentIndex(8);
    m_backButton->show();
}

// OpenCV检测
void MainWindow::onOpenCVClicked()
{
    m_stackedWidget->setCurrentIndex(9);
    m_backButton->show();
}

// 画图工具
void MainWindow::onPaintClicked()
{
    m_stackedWidget->setCurrentIndex(10);
    m_backButton->show();
}

// 壁纸切换
void MainWindow::onWallpaperClicked()
{
    // 壁纸切换不打开新页面，直接切换主题
    m_currentTheme = (m_currentTheme + 1) % 2; // 在0和1之间切换
    loadStyleSheet(m_currentTheme);
    qDebug() << "切换到主题:" << m_currentTheme;
}

// 设置
void MainWindow::onSettingsClicked()
{
    m_stackedWidget->setCurrentIndex(11);
    m_backButton->show();
}

// 返回主页
void MainWindow::onBackToHome()
{
    // 获取当前页面索引，进行资源清理
    int currentIndex = m_stackedWidget->currentIndex();
    
    // 根据不同的页面进行相应的资源清理
    switch (currentIndex) {
    case 1: // 串口助手
        // 串口助手返回时关闭串口
        if (m_serialWidget) {
            qDebug() << "离开串口助手页面";
            m_serialWidget->cleanup(); // 调用清理方法
        }
        break;
        
    case 3: // MQTT测试
        // MQTT返回时断开连接
        if (m_mqttWidget) {
            qDebug() << "离开MQTT测试页面";
            m_mqttWidget->cleanup(); // 调用清理方法
        }
        break;
        
    case 4: // 视频播放器
        // 视频播放器返回时停止播放，释放资源
        if (m_videoWidget) {
            qDebug() << "离开视频播放器页面，停止播放并释放资源";
            m_videoWidget->cleanup(); // 调用清理方法
        }
        break;
        
    case 5: // 音乐播放
        // 音乐播放器返回时停止播放
        qDebug() << "离开音乐播放器页面";
        break;
        
    case 7: // 照相机
        // 摄像头返回时关闭摄像头
        qDebug() << "离开照相机页面";
        break;
        
    default:
        break;
    }
    
    // 切换到主页
    m_stackedWidget->setCurrentIndex(0);
    m_backButton->hide();
}

// 更新系统信息
void MainWindow::onUpdateSystemInfo()
{
    updateSystemInfo();
}

